package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import models.Login;

public class LoginDAO {

	Connection conexao;

	public LoginDAO(Connection openConexaoBanco) {
		this.conexao = openConexaoBanco;
	}

	public List<Login> listarTodos() {
		List<Login> listaLogins = new ArrayList<Login>();
		
		
		try {
			String comando = "select * from login";
			java.sql.Statement start = conexao.createStatement();
			ResultSet rs = start.executeQuery(comando);
			
			while(rs.next()){
				Login login = new Login();
				int idLogin = Integer.parseInt(rs.getString("id"));
				
				login.setId(idLogin);
				login.setLogin(rs.getString("login"));
				login.setSenha(rs.getString("senha"));
			
				listaLogins.add(login);
			}
			
			
			
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		return listaLogins;
	}

	public boolean cadastrar(Login lo) {
		// TODO Auto-generated method stub
		
		boolean retorno = false;
		try {
			String comando = "insert into login (login, senha)"
				+ "values(?,?)";
			
			PreparedStatement p = this.conexao.prepareStatement(comando);
			
			p.setString(1, lo.getLogin());
			p.setString(2, lo.getSenha());
			
			p.execute();
			retorno = true;
			
		} catch (SQLException e) {
			System.out
					.println("Ocorreu erro na hora de inserir o Login try catch");
			e.printStackTrace();
		}
		return retorno;
	}

	public Login buscarLogin(String username) {
		Login login = new Login();
		try {
			String comando = "select id,login, senha from login where login='"+username+"';";
			java.sql.Statement start = conexao.createStatement();
			ResultSet rs = start.executeQuery(comando);
			while(rs.next()){
				int idLogin = Integer.parseInt(rs.getString("id"));
				
				login.setId(idLogin);
				login.setLogin(rs.getString("login"));
				login.setSenha(rs.getString("senha"));
				break;
			}
		
		} catch (SQLException e) {
			System.out
					.println("Ocorreu erro na hora de buscar o Login try catch");
			e.printStackTrace();
		}
		
		return login;
	}

	public void excluirLogin(String _id) {
		String comando = "delete from login where id=?;";
		try {
			PreparedStatement p = this.conexao.prepareStatement(comando);
			p.setString(1, _id);
			
			p.execute();
		} catch (SQLException e) {
			System.out.println("Ocorreu erro na hora de excluir a LOGIN try catch");
			e.printStackTrace();
		}
		
	}

}
